<template>
  <div class="add">
    <!-- 新增 -->
    <el-form ref="addform" :model="addform" size="mini"  :rules="rules" width="100%">
      <el-form-item v-if="isAdd" prop="usrCode" label="用户账号" :label-width="formwidth" size="mini" >
            <el-input :disabled="disabled" v-model="addform.usrCode" clearable style="width:100%" maxlength="50" ></el-input>
      </el-form-item>
       <el-form-item v-else prop="usrCode" label="用户账号" :label-width="formwidth" size="mini" >
            <el-input :disabled="true" v-model="addform.usrCode" clearable style="width:100%" maxlength="50" ></el-input>
      </el-form-item>
      <el-form-item prop="usrName" label="用户名称" :label-width="formwidth" size="mini">
            <el-input :disabled="disabled" auto-complete="new-password" v-model="addform.usrName" clearable maxlength="25" ></el-input>
      </el-form-item>
      <el-form-item v-if="isAdd" prop="usrPassword" label="账号密码" :label-width="formwidth" size="mini">
            <el-input :disabled="disabled" auto-complete="new-password" v-model="addform.usrPassword" clearable show-password maxlength="20" ></el-input>
      </el-form-item>
      <el-form-item v-if="isAdd" prop="reusrPassword" label="密码确认" :label-width="formwidth" size="mini">
            <el-input :disabled="disabled" auto-complete="new-password" v-model="addform.reusrPassword" clearable show-password maxlength="20" ></el-input>
      </el-form-item>
      <el-form-item prop="usrRles" label="角色" :label-width="formwidth" size="mini">
            <el-select :disabled="disabled" multiple style="width: 100%;" v-model="addform.usrRles" filterable>
              <el-option
              v-for="item in roleData"
              :key="item.uuid"
              :label="item.rleName"
              :value="item.uuid"
              >
              </el-option>
            </el-select>
      </el-form-item>
      <el-form-item style="position: relative;" prop="usrDpts" label="部门"  :label-width="formwidth" size="mini">
        <el-popover
          :disabled="disabled"
          placement="bottom-start"
          trigger="click"
          :appendToBody="false"
          :width="width"
          :popper-options="{
            boundariesElement: 'scrollParent',
          }"
          v-model="showpop">
            <el-tree
            :props="defaultProps"
            node-key="id"
            show-checkbox
            check-strictly
            default-expand-all
            :data="departData"
            ref="tree"
            @check="chose"
            @node-click="chose"
            >
            </el-tree>
          <el-input :disabled="disabled" ref="widthRef" slot="reference" placeholder="点击选择上级部门" v-model="addform.dptName" size="mini" clearable></el-input>
        </el-popover>
      </el-form-item>
       <el-form-item prop="usrCellphone" label="联系电话" :label-width="formwidth" size="mini">
            <el-input :disabled="disabled" v-model="addform.usrCellphone"></el-input>
      </el-form-item>
      <el-form-item prop="usrEmail" label="邮箱" :label-width="formwidth" size="mini">
            <el-input :disabled="disabled" v-model="addform.usrEmail" clearable></el-input>
      </el-form-item>
      <el-form-item prop="usrStatus" label="状态" :label-width="formwidth" size="mini">
            <el-select :disabled="disabled" style="width: 100%;" v-model="addform.usrStatus"  filterable>
              <el-option
              v-for="item in status"
              :key="item.code"
              :label="item.name"
              :value="item.code"
              >
              </el-option>
            </el-select>
      </el-form-item>
      <el-form-item prop="remark" label="备注" :label-width="formwidth" size="mini">
            <el-input :disabled="disabled" type="textarea" v-model="addform.remark" maxlength="150" show-word-limit></el-input>
      </el-form-item>
    </el-form>
    <div class="el-dialog__footer">
      <el-button size="mini" @click="cancel">关闭</el-button>
      <el-button v-if="!disabled" size="mini" type="primary" @click="save">保存</el-button>
    </div>
  </div>
</template>>
<script>
import {queryrolesGys} from '@/request/api'
import resize from '@/mixins/resize'

export default {
  mixins: [resize],
  created () {
    this.resize = () => {
      this.width = this.$refs.widthRef.$el.offsetWidth
    }
  },
  mounted(){
    // console.log(this.form);
    queryrolesGys({
      rleCUuid:'g'}
    ).then(res=>{
      this.roleData=res.data
    })
    this.$refs.addform.resetFields()
    if (!this.isAdd) {
      this.initSelectNode()
    }

  },
  computed: {
    isAdd () {
      return this.dialogmode === this.DIALOG_MODE.ADD
    },
    disabled () {
      return this.dialogmode === this.DIALOG_MODE.VIEW
    },
    rules () {
      let checkPwd=(rule,value,callback)=>{
        if (value !== this.addform.usrPassword) {
          callback(new Error('两次输入密码不一致!'))
        } else {
          callback()
        }
      }
      return {
        usrCode:[{required:true,message:'请输入用户账号',trigger:['blur','change']},
          {max:50,message:'输入字符请不要超过50个字段',trigger:['blur','change']}],
        usrName:[{required:true,message:'请输入用户名称',trigger:['blur','change']},
          {max:25,message:'输入字符请不要超过25个字段',trigger:['blur','change']}],
        usrPassword:[{required:this.isAdd,message:'密码不能为空,请输入用户密码',trigger:['blur','change']},
          {pattern:/^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_]+$)(?![a-z0-9]+$)(?![a-z\W_]+$)(?![0-9\W_]+$)[a-zA-Z0-9\W_]{8,20}$/,
            max:20,min:8,message:'输入密码为数字、小写字母、大写字母至少三种8-20位',trigger:['blur','change']}],
        reusrPassword:[{required:this.isAdd,message:'密码不能为空，请输入密码',trigger:['blur','change']},
          { validator: checkPwd, trigger: 'blur' },
          {max:20,message:'输入字符请不要超过20个字段',trigger:['blur','change']}],
        usrRles:[{required:true,message:'请输入角色',trigger:['blur','change']}],
        usrDpts:[{required:true,message:'请输入部门',trigger:['blur','change']}],
        // usrCellphone:[{pattern:/^\d{11}$/,message:'请输入11位手机号',trigger:['blur','change']}],
        usrEmail:[{pattern:/^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/,message:'输入邮箱格式不正确',trigger:['blur','change']}],
        usrStatus:[{required:true,message:'请选择状态',trigger:['blur','change']}],
        remark:[{max:150,message:'最多可以输入150个字符',trigger:['blur','change']}]
      }

    },
  },

  props:{
    departData:{
      type:Object,
      required:true
    },
    form: {
      type: Object,
      required: true
    },
    dialogmode: {}
  },

  data(){

    return{
      width: 0,
      showpop: false,
      addform: this.form,
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      formwidth:'10rem',

      //状态
      status:[{
        name:'可用',
        code:'Y'
      },
      {
        name:'不可用',
        code:'N'
      }],
      //角色
      roleData:[],
    }
  },
  methods:{
    cancel(){
      this.$emit('cancel')
    },
    chose () {
      let names = []
      let ids = []
      this.$refs.tree.getCheckedNodes().forEach((item) => {
        names.push(item.name)
        ids.push(item.id)
      })
      this.addform.dptName = names.join(',')
      this.addform.usrDpts = ids
    },
    save(){
      this.$refs.addform.validate(valid => {
        if (valid) {
          this.$emit('save',this.addform)
        }
      })
    },
    // 编辑时初始化部门下拉框
    // 由于是树状的结构 使用了递归处理节点
    initSelectNode () {
      let usrDpts = this.addform.usrDpts
      let tree = this.departData
      let selectNodes = []
      const checkNodes = (nodes) => {
        nodes.forEach(item => {
          if (item.id && usrDpts.includes(item.id)) {
            selectNodes.push(item)
          }
          if (item.children) {
            checkNodes(item.children)
          }
        })
      }
      checkNodes(tree)
      this.addform.dptName = selectNodes.map(item => item.name).join(',')
      this.$refs.tree.setCheckedNodes(selectNodes)

    }
  }
}
</script>
<style lang="scss" scoped>
.add{
  width:100%;
  // .dialog-footer{
  //   float:right;
  // }
}
</style>
